package com.auctionhaus



class Listing {

    String listName
    Date creationDate
    Date endDateTime
    Double startBidPrice
    Double maxBidPrice
    Double nextBidPrice
    //Set bids

    static hasMany = [bids:Bid]
    String description
    Customer seller
    Customer winner

    static belongsTo = [seller:Customer]

    static transients = [ 'maxBidPrice', 'nextBidPrice', 'numberOfBids', 'maxBid']

    static constraints = {
      description(nullable:true, size:0..256)
      listName(size:1..64)
      winner(nullable:true)
      startBidPrice(nullable:false )
      endDateTime(nullable:false, validator: { val, obj -> obj.properties['endDateTime'] >= new Date()
                })
      creationDate(nullable:false)
      winner(nullable:true)
    }

    static mapping = {
        seller updateable: false
        winner updateable: false
    }
    String toString() {
        listName
    }

    Double getNextBidPrice() {
        getMaxBidPrice() + Bid.incrementRate
    }
    Double getMaxBidPrice() {
           if (this.bids?.size() > 0)
                this.bids.collect{bid -> bid.amount}.max()
           else
                startBidPrice
    }
    Bid getMaxBid() {
        Bid maxBid = bids?.asList()[0]
        if (maxBid){
            bids.each {Bid b ->
                if (b.amount >= maxBid.amount) {
                    maxBid = b
                }
            }
        }
        return maxBid
    }

    Integer getNumberOfBids() {
        if (bids?.asList()?.size() > 0)
            bids.asList().size()
        else
            0
    }

    List<Listing> getCurrentListings() {
        def results = Listing.createCriteria().list() {
            ge("endDateTime", new Date())
        }
    }

}
